package com.example.passport.service;

import com.example.common.dto.ListDto;
import com.example.common.dto.Pagination;
import com.example.common.exception.BusinessException;
import com.example.common.util.StrUtil;
import com.example.front.entity.Department;
import com.example.front.entity.Event;
import com.example.front.mapper.BoxMapper;
import com.example.front.mapper.DepartmentMapper;
import com.example.front.serivce.EventService;
import com.example.interceptor.UserContext;
import com.example.passport.dto.RoleDto;
import com.example.passport.dto.TokenDto;
import com.example.passport.dto.UserDto;
import com.example.passport.entity.Logging;
import com.example.passport.entity.Role;
import com.example.passport.entity.User;
import com.example.passport.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.util.StringUtils;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserService {

    @Resource
    UserMapper userMapper;
    @Resource
    EventService eventService;
    @Resource
    BoxMapper boxMapper;
    @Resource
    DepartmentMapper departmentMapper;

    /**
     * 新增用户
     */
    public void createUser(User user, String password) {

        if (userMapper.findByMobile(user.getMobile()) != null) {
            throw new BusinessException("手机号已注册");
        }

        String passwordSalt = StrUtil.randomString(32);
        String passwordHash = StrUtil.md5(password + passwordSalt);
        user.setPasswordSalt(passwordSalt);
        user.setPasswordHash(passwordHash);
        user.setCreatedAt(new Date());

        System.out.println(user);

        userMapper.create(user);
    }

    /**
     * 查找用户
     */
    public User findUserById(Long userId) {
        User user = userMapper.findByIdTd(userId);
        if (user != null) {
            if (user.getSuperiorId() != 0) {
                User superior = userMapper.findByIdTd(user.getSuperiorId());
                user.setSuperiorName(superior.getName());
            } else {
                user.setSuperiorName("");
            }
            if (user == null) {
                User user1 = User.builder().name("").build();
                return user1;
            }
        }
        return user;
    }

    /**
     * 查找用户(包括已经删除的)
     */
    public User findUserByIdAndDel(Long userId) {
        User user = userMapper.findByIdAndDel(userId, UserContext.getUser().getTenantId());
        if (user != null) {
            if (user.getSuperiorId() != 0) {
                User superior = userMapper.findByIdAndDel(user.getSuperiorId(), UserContext.getUser().getTenantId());
                user.setSuperiorName(superior.getName());
            } else {
                user.setSuperiorName("");
            }
            if (user == null) {
                User user1 = User.builder().name("").build();
                return user1;
            }
        }
        return user;
    }

    /**
     * 查找用户
     */
    public User findById(Long userId) {
        User user = userMapper.findById(userId);
        if (user == null) {
            User user1 = User.builder().name("").build();
            return user1;
        }
        if (user.getSuperiorId() != 0) {
            user = userMapper.findById(userId);
            User superior = userMapper.findById(user.getSuperiorId());
            user.setSuperiorName(superior.getName());
        }
        return user;
    }

    /**
     * 列出用户
     */
    public ListDto<UserDto> listUser(User condition, Pagination pagination) {
        long total = userMapper.count(condition);
        if (total <= 0) {
            return new ListDto<>(new ArrayList<>(), pagination);
        }

        pagination.setTotal(total);

        List<User> userList = userMapper.findAll(condition, pagination);
        List<UserDto> userDtoList = userList.stream().map(user -> {
            UserDto userDto = new UserDto();
            List<String> list = new ArrayList<>();
            List<Long> ids = new ArrayList<>();
//            if(user.getEventId()!=null){
//                for (String s : user.getEventId().split(",")) {
//                    list.add(eventService.findById(UserContext.getUser().getTenantId(),Long.parseLong(s)));
//                    ids.add(Long.parseLong(s));
//                }
//            }
            BeanUtils.copyProperties(user, userDto);
            userDto.setEventName(StringUtils.join(list, ","));
            userDto.setEventId(ids);

            Department department = new Department();
            if (user.getDepId() == null){
                department.setId(0l);
            }else{
                department.setId(user.getDepId());
            }
            department.setTenantId(user.getTenantId());
            Department dep = departmentMapper.find(department);
            if (dep != null){
                userDto.setDepName(dep.getName());
            }

            if (userDto.getSuperiorId()!=0){
                User superior = userMapper.findById(userDto.getSuperiorId());
                if (superior != null) {
                    userDto.setSuperiorName(superior.getName());
                } else {
                    userDto.setSuperiorName("");
                }
            } else {
                userDto.setSuperiorName("");
            }
            return userDto;
        }).collect(Collectors.toList());

        return new ListDto<>(userDtoList, pagination);
    }

    /**
     * 修改密码
     */
    public void updatePassword(User user, String oldPwd, String newPwd) {
        if (!StrUtil.md5(oldPwd).equals(user.getPasswordHash())) {
            throw new BusinessException("密码验证错误");
        }
        if (userMapper.updatePassword(user.getId(), user.getTenantId(), StrUtil.md5(newPwd)) == 0) {
            throw new BusinessException("密码修改失败");
        }
    }

    /**
     * 修改状态
     */
    public void updateStatus(long userId, int status, User user) {
        if (user.getId() == userId) {
            throw new BusinessException("不允许修改自己");
        }
        if (userMapper.updateStatus(userId, user.getTenantId(), status) != 1) {
            throw new BusinessException("操作失败");
        }
    }

    /**
     * 查修用户名
     */
    public String findNameById(Long userId) {
        User user = userMapper.findByIdTd(userId);
        if (user == null) {
            throw new BusinessException("查无此人");
        }
        return user.getName();
    }

    /**
     * 修改数据
     */
    public void update(@Valid UserDto userDto) {
        User me = UserContext.getUser();
        if (userMapper.findByUserName(userDto.getUsername(), me.getTenantId()) != null && userMapper.findByIdUserName(me.getTenantId(), userDto.getId(), userDto.getUsername()) == null) {
            throw new BusinessException("用户名已存在");
        }
        if (userMapper.findByMobile(userDto.getMobile()) != null && userMapper.findByIdMobile(me.getTenantId(), userDto.getId(), userDto.getMobile()) == null) {
            throw new BusinessException("手机号已存在");
        }
//        if (userDto.getId().equals(userDto.getSuperiorId())) {
//            throw new BusinessException("请选择其他上级领导");
//        }
        User user = new User();
        BeanUtils.copyProperties(userDto, user);
        user.setTenantId(me.getTenantId());
        user.setEventId(StringUtils.join(userDto.getEventId(), ","));
        System.out.println(user);
        if (userMapper.update(user) < 1) {
            throw new BusinessException("操作失败");
        }
    }

    /**
     * 删除数据
     */
    public void delete(long id) {
        if (userMapper.deleteById(id, UserContext.getUser().getTenantId()) != 1) {
            throw new BusinessException("操作失败");
        }
    }

}
